import { ComponentInfoType, ComponentStateType } from ".";

export function getNextSelectId(
  componentList: ComponentInfoType[],
  selectId: string
) {
  const visibleComponentList = componentList.filter((c) => !c.isHidden);
  const index = visibleComponentList.findIndex((c) => c.fe_id === selectId);
  if (index < 0) return "";

  //重新计算select ID
  let newSelectedId = "";
  const len = componentList.length;
  if (len <= 1) {
    newSelectedId = "";
  } else {
    // 组件长度大于1
    if (index + 1 >= len) {
      //删除最后一个，就要选中上一个就是 -1
      newSelectedId = componentList[index - 1].fe_id;
    } else {
      // 删除不是最后一个就是选中下一个 +1
      newSelectedId = componentList[index + 1].fe_id;
    }
  }
  return newSelectedId;
}

/**
 * 新增组件时，计算新的selectId
 */
export function inserNewComponent(
  draft: ComponentStateType,
  newComponent: ComponentInfoType
) {
  const { selectId, componentList } = draft;
  const index = componentList.findIndex((item) => item.fe_id === selectId);

  //如果没有选中组件，直接添加到最后
  if (index < 0) draft.componentList.push(newComponent);
  //如果有选中组件，添加到选中组件后面
  else draft.componentList.splice(index + 1, 0, newComponent);

  draft.selectId = newComponent.fe_id;
}
